﻿using BigMonitoringWarningApi.Model.ApiResult;
using GYCTOAManagementSystemNewApi.Model.Request;
using GYCTOAManagementSystemNewApi.Model;
using GYCTOAManagementSystemNewApi.Public;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using System;
using System.Linq;
using Newtonsoft.Json;
using Microsoft.Extensions.Logging;
using GYCTOAManagementSystemNewApi.Model.Tool;
using System.Data.Entity;
using GYCTOAManagementSystemNewApi.Model.Response.FinanceReimbursementReimRe;
using WebSocketSharp.Frame;
using Microsoft.CodeAnalysis;
using GYCTOAManagementSystemNewApi.Model.Response;
using GYCTOAManagementSystemNewApi.Model.Enum;
using GYCTOAManagementSystemNewApi.Model.Entity;
using GYCTOAManagementSystemNewApi.Model.Enum.PayrollForm;
using System.Collections.Generic;
using GYCTOAManagementSystemNewApi.Tool;
using BigMonitoringWarningApi.Tool.Extension;
using System.Data;
using Top.Api;
using Microsoft.CodeAnalysis.VisualBasic.Syntax;
using Microsoft.EntityFrameworkCore.Metadata.Internal;

namespace GYCTOAManagementSystemNewApi.Controllers
{
    /// <summary>
    /// 报销单
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    //[Authorize]

    public class NewFinanceReimbursementReim : Controller
    {

        private readonly ILogger<LoginController> _logger;
        DBContext _db;
        // private static IHostingEnvironment _hostingEnvironment;
        public NewFinanceReimbursementReim(ILogger<LoginController> logger, DBContext context)
        {
            _logger = logger;
            _db = context;
        }
        #region 豪度报销
        /// <summary>
        ///获取报销类型
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetFinanceLoanResEnum")]
        public ApiResult GetFinanceLoanResEnum()
        {
            var type = typeof(GYCTOAManagementSystemNewApi.Model.Enum.PayrollForm.FinanceLoanResEnum);
            var data = Enum.GetValues(type)
                       .Cast<GYCTOAManagementSystemNewApi.Model.Enum.PayrollForm.FinanceLoanResEnum>()
                       .Select(e => new GetEnumtResponse
                       {
                           Description = command.GetEnumDescription(e),
                           Value = Convert.ToInt32(e),
                       })
                       .ToList();
            return ApiResult.True(data);
        }

        /// <summary>
        ///获取报销类型
        /// </summary>
        /// <returns></returns>
        [HttpPost("SetFinanceReimbursementReiMoney")]
        public ApiResult SetFinanceReimbursementReiMoney()
        {
            var financeReimbursementReim = _db.FinanceReimbursementReim.Where(x => !x.Delete).ToList();

            foreach (var item in financeReimbursementReim)
            {
            var money=   Convert.ToDouble( _db.ReimRule.Where(x => x.FinanceReimbursementId == item.Id && !x.Delete).Sum(j
                    => j.ReimRuleMoney));
                if (money!=0)
                {
                    item.Money = money;
                }
            }
            _db.UpdateRange(financeReimbursementReim);
            _db.SaveChanges();
            return ApiResult.True();
        }
        #region 检查报销单是否开帐


        /// <summary>
        /// 检查报销单是否开帐
        /// </summary>
        /// <returns></returns>
        [HttpPost("CheckSettlement")]
        public ApiResult CheckSettlement([FromBody] CheckSettlementRequest request)
        {
            var Checksettlement = _db.FinanceReimbursementReim.FirstOrDefault(x => x.SettlementNumber == request.SettlementNumber
            && x.Settlement && !x.Delete && x.ProjectId.Equals(request.ProjectId));
            if (Checksettlement != null)
            {
                return ApiResult.False($"当前年份编号{Checksettlement.ReimNumber}已开帐，是否修改开帐订单,修改后社保数据将清除重新开帐时请重新填写.");

            }
            return ApiResult.True();
        }



        /// <summary>
        /// 设置开账数据；2025年7月25日弃用，将之前的批量年度开账改为单条记录单独开账
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("SetSettlement1")]
        public ApiResult SetSettlement1([FromBody] SetSettlementRequest request)
        {
            try
            {
                using (var transaction = _db.Database.BeginTransaction())
                {
                    try
                    {
                     var financeReimbursementReim= _db.FinanceReimbursementReim.Where(x => x.ProjectId == request.Projectid).ToList();

                          // 获取年份结算数据
                          var settlements = financeReimbursementReim
                            .Where(x => x.Settlement && !x.Delete)
                            .OrderByDescending(x => x.SettlementNumber)
                            .ToList();
                        // 当前选择年份开账
                        var Checksettlement = financeReimbursementReim
                            .FirstOrDefault(x => x.SettlementNumber == request.SettlementNumber && x.Settlement && !x.Delete);
                        // 当前所选新开账年数据
                        var ChecksettlementById = financeReimbursementReim
                            .FirstOrDefault(x => x.Id == request.OrderId);

                        if (ChecksettlementById == null)
                        {
                            return ApiResult.False("未找到对应的订单");
                        }
                        #region 废弃
                        //// 处理已有结算记录的情况
                        //if (settlements.Any() && Checksettlement != null)
                        //{
                        //    Checksettlement.Settlement = false;
                        //    string SettlementNumber = string.Empty;
                        //    List<FinanceReimbursementReim> UpFinanceReimbursementReims = new();

                        //    var index = settlements.IndexOf(Checksettlement);
                        //    HandleExistingSettlement(Checksettlement, ChecksettlementById, settlements, index, request, out UpFinanceReimbursementReims, out SettlementNumber);
                        //    UpdateSettlementRecords(UpFinanceReimbursementReims, SettlementNumber,request);
                        //}
                        //// 处理第一次或最新开账的情况
                        //if (settlements.Count == 0)
                        //{
                        //    HandleFirstOrLatestSettlement(request, ChecksettlementById);
                        //}

                        ////新年份开账
                        //if(Checksettlement == null && settlements.Count != 0)
                        //{
                        //    HandleUpdateNewYear(settlements, financeReimbursementReim, ChecksettlementById, request);
                        //}
                        #endregion

                        #region 新版
                        //新年份开账
                        if (Checksettlement == null)
                        {
                            HandleUpdateNewYear(settlements, financeReimbursementReim, ChecksettlementById, request);
                        }
                        else
                        {
                            Checksettlement.Settlement = false;
                            string SettlementNumber = string.Empty;
                            List<FinanceReimbursementReim> UpFinanceReimbursementReims = new();
                            var index = settlements.IndexOf(Checksettlement);
                            HandleExistingSettlement(Checksettlement, ChecksettlementById, settlements, index, request, out UpFinanceReimbursementReims, out SettlementNumber);
                            UpdateSettlementRecords(UpFinanceReimbursementReims, SettlementNumber, request);
                        }

                        #endregion




                        // 更新目标记录
                        UpdateTargetRecord(request, ChecksettlementById);

                        // 提交事务
                        _db.SaveChanges();
                        transaction.Commit();
                        return ApiResult.True("修改成功");
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        _logger.LogWarning(JsonConvert.SerializeObject(ex));
                        return ApiResult.False($"系统错误: {ex.Message}");
                    }
                }
            }
            catch (Exception e)
            {
                _logger.LogWarning(JsonConvert.SerializeObject(e));
                return ApiResult.False($"系统错误: {e.Message}");
            }
        }
        /// <summary>
        /// 设置开账数据；2025年7月25日弃用，将之前的批量年度开账改为单条记录单独开账
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("SetSettlement")]
        public ApiResult SetSettlement([FromBody] SetSettlementRequest request)
        {
            try
            {
                using (var transaction = _db.Database.BeginTransaction())
                {
                    try
                    {
                        // 当前所选新开账年数据
                        var ChecksettlementById = _db.FinanceReimbursementReim.FirstOrDefault(x => x.Id == request.OrderId && !x.Delete);
                        if (ChecksettlementById == null)
                        {
                            return ApiResult.False("未找到对应的报销单，请检查单据是否已删除");
                        }
                        if (ChecksettlementById.FinanceReimbursementStart == OrderStateEnum.WaitApprove)
                        {
                            return ApiResult.False("该单据未通过审核，请先审核通过后再进行开账操作");
                        }

                        // 更新目标记录
                        UpdateTargetRecord(request, ChecksettlementById);

                        // 提交事务
                        _db.SaveChanges();
                        transaction.Commit();
                        return ApiResult.True("修改成功");
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        _logger.LogWarning(JsonConvert.SerializeObject(ex));
                        return ApiResult.False($"系统错误: {ex.Message}");
                    }
                }
            }
            catch (Exception e)
            {
                _logger.LogWarning(JsonConvert.SerializeObject(e));
                return ApiResult.False($"系统错误: {e.Message}");
            }
        }

        private void HandleExistingSettlement(
            FinanceReimbursementReim OldChecksettlement,
            FinanceReimbursementReim NewChecksettlementById,
            List<FinanceReimbursementReim> settlements,
            int index,
            SetSettlementRequest request,
            out List<FinanceReimbursementReim> UpFinanceReimbursementReims,
            out string SettlementNumber)
        {
            #region MyRegion
            //UpFinanceReimbursementReims = new List<FinanceReimbursementReim>();
            //SettlementNumber = string.Empty;
            //var financeReimbursementReim = _db.FinanceReimbursementReim.Where(x => x.ProjectId == request.Projectid).ToList();

            //if (ChecksettlementById.BorrowTime > Checksettlement.BorrowTime)
            //{
            //    UpFinanceReimbursementReims = financeReimbursementReim
            //        .Where(x => x.BorrowTime >= Checksettlement.BorrowTime && x.BorrowTime <= ChecksettlementById.BorrowTime)
            //        .ToList();

            //    if ( settlements.Count==1 && index==0)
            //    {

            //        int.TryParse(settlements[index].SettlementNumber, out var number);
            //        throw new Exception($"当前无 ：{number-1}年度信息，当前开账无法前移 ");
            //    }
            //    SettlementNumber = settlements[index + 1].SettlementNumber;
            //}
            //else if (ChecksettlementById.BorrowTime < Checksettlement.BorrowTime)
            //{
            //    UpFinanceReimbursementReims = financeReimbursementReim
            //        .Where(x => x.BorrowTime <= Checksettlement.BorrowTime && x.BorrowTime >= ChecksettlementById.BorrowTime)
            //        .ToList();
            //    SettlementNumber = request.SettlementNumber;
            //}
            //else if (ChecksettlementById.BorrowTime == Checksettlement.BorrowTime)
            //{
            //    var settlement = settlements[index];
            //    if (index + 1 < settlements.Count)
            //    {
            //        settlement = settlements[index + 1];
            //        UpFinanceReimbursementReims = financeReimbursementReim
            //            .Where(x => !x.Delete && x.BorrowTime < settlement.BorrowTime)
            //            .ToList();
            //    }
            //    else
            //    {
            //        //当前开张年份不是最大年份,取出最大年份的时间
            //        var maxyearData = settlements[index - 1];
            //        UpFinanceReimbursementReims = financeReimbursementReim
            //            .Where(x => !x.Delete && x.BorrowTime >= settlement.BorrowTime && x.BorrowTime< maxyearData.BorrowTime)
            //            .ToList();
            //    }
            //    SettlementNumber = request.SettlementNumber;
            //}
            #endregion
            int numberIndex = settlements.FindIndex(x => x.SettlementNumber.Equals(request.SettlementNumber));
            var financeReimbursementReim = _db.FinanceReimbursementReim.Where(x => x.ProjectId == request.Projectid).ToList();
            if (OldChecksettlement.BorrowTime > NewChecksettlementById.BorrowTime)
            {
                SettlementNumber = request.SettlementNumber;
                //不是最大,也不是最小
                if (numberIndex != 0)
                {
                    UpFinanceReimbursementReims = financeReimbursementReim.Where(x => x.BorrowTime >= NewChecksettlementById.BorrowTime && x.BorrowTime <= OldChecksettlement.BorrowTime).ToList();

                }
                else
                {
                    UpFinanceReimbursementReims = financeReimbursementReim.Where(x => x.BorrowTime >= NewChecksettlementById.BorrowTime).ToList();
                }
            }
            else if (OldChecksettlement.BorrowTime < NewChecksettlementById.BorrowTime)
            {
                //最小年份
                if ((numberIndex + 1) == settlements.Count)
                {
                    int.TryParse(settlements[index].SettlementNumber, out var number);
                    throw new Exception($"当前无 ：{number - 1}年度信息，当前开账无法前移 ");
                }
                //中间,最大 年份(都是改变中间的差值)
                else
                {
                    UpFinanceReimbursementReims = financeReimbursementReim.Where(x => x.BorrowTime < NewChecksettlementById.BorrowTime && x.BorrowTime >= OldChecksettlement.BorrowTime).ToList();
                    //往上移动时间,需要修改的数据就变成去年的时间
                    SettlementNumber = settlements[numberIndex + 1].SettlementNumber;
                }
            }
            else
            {
                //最大年开账
                if (numberIndex == 0)
                {
                    UpFinanceReimbursementReims = financeReimbursementReim.Where(x => x.BorrowTime >= NewChecksettlementById.BorrowTime).ToList();
                    //往上移动时间,需要修改的数据就变成去年的时间
                    SettlementNumber = request.SettlementNumber;
                }
                else
                {
                    var fendingtime = settlements[numberIndex - 1].BorrowTime;
                    UpFinanceReimbursementReims = financeReimbursementReim.Where(x => x.BorrowTime >= NewChecksettlementById.BorrowTime && x.BorrowTime< fendingtime).ToList();
                    //往上移动时间,需要修改的数据就变成去年的时间
                    SettlementNumber = request.SettlementNumber;
                }
            }
        }

        private void UpdateSettlementRecords(List<FinanceReimbursementReim> UpFinanceReimbursementReims, string SettlementNumber, SetSettlementRequest request)
        {
            foreach (var item in UpFinanceReimbursementReims)
            {
                if (request.OrderId == item.Id) item.Settlement = true;
                else item.Settlement = false;
                item.SettlementNumber = SettlementNumber;
                UpdateReimRule(item.Id, SettlementNumber);
                _db.FinanceReimbursementReim.Update(item);
            }
        }

        private void HandleFirstOrLatestSettlement(SetSettlementRequest request, FinanceReimbursementReim ChecksettlementById)
        {
            var financeReimbursementReims = _db.FinanceReimbursementReim
                .Where(x => !x.Delete && x.BorrowTime >= ChecksettlementById.BorrowTime && x.ProjectId==request.Projectid)
                .ToList();

            foreach (var item in financeReimbursementReims)
            {
                item.SettlementNumber = request.SettlementNumber;
                UpdateReimRule(item.Id, request.SettlementNumber);
                _db.FinanceReimbursementReim.Update(item);
            }
        }

        private void UpdateTargetRecord(SetSettlementRequest request, FinanceReimbursementReim ChecksettlementById)
        {
            ChecksettlementById.SettlementNumber = request.SettlementNumber;
            ChecksettlementById.Settlement = true;

            var orderInfoById = _db.ReimRule
                .Where(x => x.FinanceReimbursementId == ChecksettlementById.Id)
                .ToList();

            orderInfoById.ForEach(x => x.SettlementNumber = request.SettlementNumber);
            _db.ReimRule.UpdateRange(orderInfoById);
            _db.FinanceReimbursementReim.Update(ChecksettlementById);
        }

        private void UpdateReimRule(int financeReimbursementId, string SettlementNumber)
        {
            var orderInfo = _db.ReimRule
                .Where(x => x.FinanceReimbursementId == financeReimbursementId)
                .ToList();

            orderInfo.ForEach(x => x.SettlementNumber = SettlementNumber);
            _db.ReimRule.UpdateRange(orderInfo);
        }

        private void HandleUpdateNewYear(List<FinanceReimbursementReim> Kzsj, List<FinanceReimbursementReim> Finlist, FinanceReimbursementReim ChecksettlementById, SetSettlementRequest request)
        {
            List<FinanceReimbursementReim> UpdateDate;
            string lastYear = ChecksettlementById.SettlementNumber;
            var Yearlist = Kzsj.Select(x => Convert.ToInt32(x.SettlementNumber)).Distinct().ToList();
            Yearlist.Add(Convert.ToInt32(request.SettlementNumber));
            Yearlist.Sort();
            var index = Yearlist.FindIndex(x=>x == Convert.ToInt32(request.SettlementNumber));
            if (index == 0 && Yearlist.Count != 1)
            {
                var headerDate = Finlist.Where(x => x.SettlementNumber.Equals(Yearlist[index + 1].ToString()) && x.Settlement && !x.Delete).FirstOrDefault();
                UpdateDate = Finlist.Where(x => x.BorrowTime >= ChecksettlementById.BorrowTime && x.BorrowTime < headerDate.BorrowTime).ToList();
            }
            else if (index == Yearlist.Count - 1)
            {
                UpdateDate = Finlist.Where(x => x.BorrowTime >= ChecksettlementById.BorrowTime).ToList();
            }
            else 
            {
                var headerDate = Finlist.Where(x => x.SettlementNumber.Equals(Yearlist[index + 1].ToString()) && x.Settlement && !x.Delete).FirstOrDefault();
                UpdateDate = Finlist.Where(x => x.BorrowTime >= ChecksettlementById.BorrowTime && x.BorrowTime < headerDate.BorrowTime).ToList();
            }
            UpdateSettlementRecords(UpdateDate, request.SettlementNumber, request);
        }

        /// <summary>
        /// 修改已经开帐订单,请谨慎操作
        /// </summary>
        /// <returns></returns>
        [HttpPost("UpSettlement")]
        public ApiResult UpSettlement([FromBody] CheckSettlementRequest request)
        {
            var Checksettlement = _db.FinanceReimbursementReim.FirstOrDefault(x => x.SettlementNumber == request.SettlementNumber
            && x.Settlement && !x.Delete && x.ProjectId.Equals(request.ProjectId));
            if (Checksettlement == null)
            {
                return ApiResult.True();
            }
            Checksettlement.Settlement = false;
            var reimRuleList = _db.ReimRule.Where(x => x.FinanceReimbursementId == Checksettlement.Id).ToList();
            reimRuleList.ForEach(x =>
            {
                x.Settlement = false;
            });
            _db.FinanceReimbursementReim.Update(Checksettlement);
            _db.ReimRule.UpdateRange(reimRuleList);
            _db.SaveChanges();
            return ApiResult.True();
        }
        #endregion



        /// <summary>
        /// 添加财务报销报表
        /// </summary>
        /// <param name="addHD"></param>
        /// <returns></returns>
        [HttpPost("AddHDFinanceReimbursement")]
        public async Task<ApiResult> AddHDFinanceReimbursement([FromBody] AddHDFinanceReimbursementRequest addHD)
        {
            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
            var Roleids = (TokenManage.GetTokenValues(author)[5].Value);
            var UserId = Convert.ToInt32((TokenManage.GetTokenValues(author)[0].Value));
            var role = Convert.ToString((TokenManage.GetTokenValues(author)[2].Value));
            var roleName = Convert.ToString((TokenManage.GetTokenValues(author)[5].Value));
            var projectFir = _db.Project.FirstOrDefault(x => x.Id.Equals(addHD.ProjectId));

            if (projectFir.ProjectStatus == 1)
            {

                return ApiResult.False("当前项目以完结，不允许添加内容");
            }
            //判断当前年度账单是否开帐如果开帐则不能再添加数据
            var payrollform = _db.FinanceReimbursementReim.FirstOrDefault(x => x.ProjectId.Equals(addHD.ProjectId) && (x.SettlementNumber == addHD.SettlementNumber) && x.Settlement);
            if (payrollform != null)
            {
                return ApiResult.False("当前年度账单已开帐，不能再添加数据");
            }
            var ids = ConfigurationHelper.GetConfigHeadRoleId("HeadRoleId");
            if (!((Roleids.Split(",").ToList().Contains(ids) || role.Contains(PublicTool.Admin))))
            {
                return ApiResult.False("对不起，您暂无权限添加");
            }
            var data = new FinanceReimbursementReim();
            //获取该项目下最大编号的记录
            var MaxNumberPayrollCount = _db.FinanceReimbursementReim.Where(x => x.ProjectId == addHD.ProjectId && !x.Delete).Count();
            var project = _db.Project.FirstOrDefault(x => x.Id == addHD.ProjectId);
            if (MaxNumberPayrollCount != 0)
            {
                var MaxNumberPayrollFormId = _db.FinanceReimbursementReim.Where(x => x.ProjectId == addHD.ProjectId && !x.Delete).Max(x => (x.Id));
                var MaxNumberPayrollForm = _db.FinanceReimbursementReim.FirstOrDefault(x => x.ProjectId == addHD.ProjectId && !x.Delete && x.Id == MaxNumberPayrollFormId);
                var maxPayrollNumber = MaxNumberPayrollForm.ReimNumber;
                var projectNameSX = project.ProjectNameSX;
                if (!maxPayrollNumber.Contains("-"))
                {
                    return ApiResult.False("已有的最新一条记录中的编号存在问题，不符合最新设定规律（项目名称首字母大写-数字），请修改后再添加！");
                }
                data.ReimNumber = projectNameSX + "-" + (Convert.ToInt32(maxPayrollNumber.Split('-')[1]) + 1);
            }
            else {
                data.ReimNumber = project.ProjectNameSX + "-1";
            }
            //data.ReimNumber = "HD_CWBX_" + DateTime.Now.ToString("yyyyMMddHHmmss");
            data.BorrowTime = Convert.ToDateTime(addHD.BorrowTime);
            data.ProjectId = addHD.ProjectId;

            data.ProjectName = addHD.ProjectName;
            data.FinanceReimbursementReimType = addHD.ReimType;
            data.FinanceReimbursementStart = OrderStateEnum.WaitApprove;
            data.UserId = addHD.Borrower;


            //var maxNumber = _db.FinanceReimbursementReim.Where(x => x.ProjectId.Equals(addHD.ProjectId)).Max(s=>s.SettlementNumber);
            //添加报销年度
            //data.Settlement = addHD.Settlement;
            //data.SettlementNumber = maxNumber;
            data.OperatDate = DateTime.Now;
            data.OperatId = UserId;
            data.Money = addHD.Money;
            await _db.FinanceReimbursementReim.AddAsync(data);
            await _db.SaveChangesAsync();
            addHD.reimRuleList.ForEach(x =>
            {
                x.OperatDate = DateTime.Now;
                x.OperatId = UserId;
                x.ProjectId = data.ProjectId;
                x.FinanceReimbursementStart = data.FinanceReimbursementStart;
                x.UserId = data.UserId;
                x.FinanceReimbursementReimType = data.FinanceReimbursementReimType;
                x.ReimNumber = data.ReimNumber;
                x.FinanceReimbursementId = data.Id;
                //x.Settlement = data.Settlement;
                //x.SettlementNumber = data.SettlementNumber;
            });
            await _db.ReimRule.AddRangeAsync(addHD.reimRuleList);
            await _db.SaveChangesAsync();
            var Resultdata = new DownFileProp() { id = data.Id, FileType = (int)FileTypeEnum.FinanceResFile, Type = 1 };
            return ApiResult.True(Resultdata);
        }

        /// <summary>
        /// 查询财务报销报表
        /// </summary>
        /// <param name="projectRequest">报销Id</param>
        /// <returns></returns>
        [HttpPost("SelHDFinanceReimbursement")]
        public ApiResult SelHDFinanceReimbursement([FromBody] DataPayRollRequest projectRequest)
        {
            var finas = _db.FinanceReimbursementReim.Where(x => x.ProjectId.Equals(projectRequest.Id)).ToList();
            if (projectRequest.IsDelete)
            {
                finas = finas.Where(x => x.Delete).ToList();
            }
            else
            {
                finas = finas.Where(x => !x.Delete).ToList();
            }
            
            var finass = _db.FinanceReimbursementReim.ToList();
            if (finas == null)
            {
                return ApiResult.True(new List<FinanceReimbursementReim>());
            }
         
            //开账
            if (!string.IsNullOrWhiteSpace(projectRequest.SettlementNumber))
            {
                finas = finas.Where(x => x.SettlementNumber == (projectRequest.SettlementNumber)).ToList();
            }
            else {
                //var number = finas.Max(x => x.SettlementNumber);
                //finas = finas.Where(x => x.SettlementNumber == DateTime.Now.Year.ToString()).ToList();

                if (projectRequest.StartTime != null)
                {
                    finas = finas.Where(x => x.BorrowTime >= projectRequest.StartTime).ToList();
                }
                if (projectRequest.EndTime != null)
                {
                    finas = finas.Where(x => x.BorrowTime <= projectRequest.EndTime).ToList();
                }
            }

            if (projectRequest.Borrower != 0)
            {
                finas = finas.Where(x => x.UserId == projectRequest.Borrower).ToList();
            }
            if (projectRequest.ReimType!= 0)
            {
                finas = finas.Where(x =>x.FinanceReimbursementReimType.Equals(projectRequest.ReimType)).ToList();
            }
            if (projectRequest.Status != null)
            {
                finas = finas.Where(x => x.FinanceReimbursementStart == projectRequest.Status).ToList();
            }
            finas =finas.OrderByDescending(x => x.BorrowTime).ToList(); 
            ////var data = from fina in finas
            //           select new
            //           {
            //               fina,
            //               Mony = (_db.ReimRule.Where(x => x.FinanceReimbursementId == (fina.Id) && !x.Delete).Select(x => x.ReimRuleMoney)?.ToList().Sum())?.ToString("0.00"),
            //               Content = _db.ReimRule.FirstOrDefault(x => x.FinanceReimbursementId == (fina.Id) && !x.Delete)?.ReimRuleContent,
            //               Abstract = _db.ReimRule.FirstOrDefault(x => x.FinanceReimbursementId == (fina.Id) && !x.Delete)?.Abstract,
            //           };


            //var result = data.ToList();
            //if (projectRequest.Status!=null)
            //{
            //    result= result.Where(x => x.fina.FinanceReimbursementStart == projectRequest.Status).ToList();
            //}
            return ApiResult.True(finas);
        }

        /// <summary>
        /// 查询财务报销报表
        /// </summary>
        /// <param name="projectRequest">报销Id</param>
        /// <returns></returns>
        [HttpPost("SelHDFinanceReimbursementInfo")]
        public ApiResult SelHDFinanceReimbursementInfo([FromBody] DataIdRequest projectRequest)
        {
            var reimRule = _db.ReimRule.Where(x => x.FinanceReimbursementId.Equals(projectRequest.Id) && !x.Delete).OrderBy(x => x.OperatDate).ToList();
            if (reimRule == null)
            {
                return ApiResult.True(new List<ReimRule>());
            }
            return ApiResult.True(reimRule);
        }
         
        /// <summary>
        /// 删除财务报销明细
        /// </summary>
        /// <param name="projectRequest">报销Id</param>
        /// <returns></returns>
        [HttpPost("DelReimRule")]
        public ApiResult DelReimRule([FromBody] DataIdRequest request)
        {
            try
            {
                var finas = _db.ReimRule.FirstOrDefault(x => x.Id.Equals(request.Id));
                finas.Delete = true;
                _db.ReimRule.Update(finas);
                _db.SaveChanges();
                return ApiResult.True();
            }
            catch (Exception ex)
            {
                return ApiResult.False(ex.Message);
                throw;
            }
        }
        /// <summary>
        /// 删除财务报销报表
        /// </summary>
        /// <param name="projectRequest">报销Id</param>
        /// <returns></returns>
        [HttpPost("DelHDFinanceReimbursement")]
        public ApiResult DelHDFinanceReimbursement([FromBody] DataIdRequest request)
        {
            try
            {
                var finas = _db.FinanceReimbursementReim.FirstOrDefault(x => x.Id.Equals(request.Id));
                finas.Delete = true;
                _db.FinanceReimbursementReim.Update(finas);
                _db.SaveChanges();
                return ApiResult.True();
            }
            catch (Exception ex)
            {
                return ApiResult.False(ex.Message);
                throw;
            }
        }

        /// <summary>
        /// 修改财务报销报表//包括状态修改
        /// </summary>
        /// <param name="ReimNumber">报销Id</param>
        /// <returns></returns>
        [HttpPost("UpHDFinanceReimbursement")]
        public async Task<ApiResult> UpHDFinanceReimbursement([FromBody] UpHDFinanceRequest projectRequest)
        {
            try
            {
                var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
                var Roleids = (TokenManage.GetTokenValues(author)[5].Value);
                var role = (TokenManage.GetTokenValues(author)[2].Value);
                var roles = (TokenManage.GetTokenValues(author)[5].Value);
                var UserId = Convert.ToInt32((TokenManage.GetTokenValues(author)[0].Value));
                if (projectRequest.UpOrAudit == 1)
                {
                    if (!roles.Contains("1"))
                    {
                        return ApiResult.False("对不起 您暂无权限审核");

                    }
                    projectRequest.financeReimbursementReim.FinanceReimbursementStart = OrderStateEnum.Success;
                }
                foreach (var item in projectRequest.reimRules)
                {
                    item.ProjectId = projectRequest.financeReimbursementReim.ProjectId;
                    item.FinanceReimbursementStart = projectRequest.financeReimbursementReim.FinanceReimbursementStart;
                    item.UserId = projectRequest.financeReimbursementReim.UserId;
                    item.FinanceReimbursementReimType = projectRequest.financeReimbursementReim.FinanceReimbursementReimType;
                    //修改报销年度
                    item.Settlement = projectRequest.financeReimbursementReim.Settlement;
                    item.SettlementNumber = projectRequest.financeReimbursementReim.SettlementNumber;
                    if (item.FinanceReimbursementStart == OrderStateEnum.WaitApprove)
                    {
                        projectRequest.financeReimbursementReim.FinanceReimbursementStart = OrderStateEnum.WaitApprove;
                        break;
                    }
                } 
                _db.FinanceReimbursementReim.Update(projectRequest.financeReimbursementReim);
                _db.ReimRule.UpdateRange(projectRequest.reimRules);
                await _db.SaveChangesAsync();
                return ApiResult.True();
            }
            catch (Exception ex)
            {
                return ApiResult.False(ex.Message);
                throw;
            }
        }
        /// <summary>
        /// 报销单Excel数据下载
        /// </summary>
        /// <param name="Data"></param>
        /// <returns></returns>
        [HttpPost("GetFormFinanceReimExcel")]
        public ApiResult GetFormFinanceReimExcel([FromBody] DataIdRequest Data)
        {
            try
            {
                var reimbursement = _db.FinanceReimbursementReim.Where(x => x.Id.Equals(Data.Id) && !x.Delete).FirstOrDefault();
                var reimRules = _db.ReimRule.Where(x => x.FinanceReimbursementId.Equals(reimbursement.Id) && !x.Delete).ToList();
                var project = _db.Project.FirstOrDefault(x => x.Id.Equals(reimbursement.ProjectId));
                var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
                var userId = Convert.ToString(TokenManage.GetTokenValues(author)[0].Value);
                var roleName = Convert.ToString(TokenManage.GetTokenValues(author)[2].Value);
                if (!(reimbursement.UserId.Equals(userId) || roleName.Equals(PublicTool.Admin) || project.HeadUserId.Equals(userId)))
                {
                    return ApiResult.False("您当前无权进行下载程序");
                }
                var WaitData = new List<int>();

                if (reimbursement.FinanceReimbursementStart == OrderStateEnum.WaitApprove)
                {
                    return ApiResult.False($"单据号：{reimbursement.ReimNumber} 还未审核，请审核后再次下载");
                }
                var result = new PublicTool().CreateExcelToBXD(reimRules, reimbursement, project.ProjectName);
                return ApiResult.True(result);
            }
            catch (Exception ex)
            {
                return ApiResult.False(ex.Message);
            }
        }

        /// <summary>
        /// 数据展示报销列表
        /// </summary>
        /// <param name="Data"></param>
        /// <returns></returns>
        [HttpPost("GetNewFinanceReimbursementData")]
        public ApiPageResult GetNewFinanceReimbursementData([FromBody] GetNewFinanceReimbursementDataRequest Data)
        {
            try
            {
                IQueryable<FinanceReimbursementReim> financeReim = _db.FinanceReimbursementReim.Where(x => x.FinanceReimbursementStart == OrderStateEnum.Success && !x.Delete);
                if (Data.UserId.HasValue)
                {
                    financeReim = financeReim.Where(x => x.UserId == Data.UserId);
                }
                if (Data.ProjectId.HasValue)
                {
                    financeReim = financeReim.Where(x => x.ProjectId == Data.ProjectId);
                }
                if (Data.FinanceReimbursementReimType.HasValue)
                {
                    financeReim = financeReim.Where(x => x.FinanceReimbursementReimType == Data.FinanceReimbursementReimType);
                }
                if (Data.CreateTime.HasValue)
                {
                    financeReim = financeReim.Where(x => x.BorrowTime.Date >= Data.CreateTime.Value.Date);
                }
                if (Data.EmdTime.HasValue)
                {
                    financeReim = financeReim.Where(x => x.BorrowTime.Date <= Data.EmdTime.Value.Date);
                }
                var datarelust = financeReim.OrderBy(x => x.Id).ToList();
                var rows = datarelust.Skip(Data.PageSize * (Data.PageIndex - 1)).Take(Data.PageSize).ToList();
                return ApiPageResult.True(rows, Data.PageIndex, Data.PageSize, datarelust.Count);
            }
            catch (Exception ex)
            {
                return ApiPageResult.False(new { }, Data.PageIndex, Data.PageSize, $"程序出现问题：{ex.Message},请联系开发相关人员");
            }
        }
        #endregion
    }
}
